/**
 * @file link_stack.cpp
 * @brief 链栈实现
 * @author Xavier ZXY (zxy_xavier@163.com)
 * @version : 1.0
 * @date 2022-04-24
 *
 */

#include "link_stack.h"
#include <stdio.h>
#include <stdlib.h>

int main()
{

    int j;
    LinkStack s;
    int e;
    if (InitStack(&s) == OK)
        for (j = 1; j <= 10; j++)
            Push(&s, j);
    printf("栈中元素依次为：");
    StackTraverse(s);
    Pop(&s, &e);
    printf("弹出的栈顶元素 e=%d\n", e);
    printf("栈空否：%d(1:空 0:否)\n", StackEmpty(s));
    GetTop(s, &e);
    printf("栈顶元素 e=%d 栈的长度为%d\n", e, StackLength(s));
    ClearStack(&s);
    printf("清空栈后，栈空否：%d(1:空 0:否)\n", StackEmpty(s));
    return 0;

    return 0;
}

//显示元素
Status visit(SElemType c)
{
    printf("%d ", c);
    return OK;
}

//构造一个空栈
Status InitStack(LinkStack *S)
{
    S->top = (LinkStackPtr)malloc(sizeof(StackNode));
    if (!S->top)
    {
        return ERROR;
    }
    S->top = nullptr;
    S->cnt = 0;

    return OK;
}

//把S置为空栈
Status ClearStack(LinkStack *S)
{
    LinkStackPtr p, q;
    p = S->top;
    while (p)
    {
        q = p;
        p = p->next;
        free(q);
    }

    S->cnt = 0;

    return OK;
}

// S是否为空栈
Status StackEmpty(LinkStack S)
{
    if (S.cnt == 0)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

// S的元素个数，即栈长
int StackLength(LinkStack S)
{
    return S.cnt;
}

//返回栈顶元素
Status GetTop(LinkStack S, SElemType *e)
{
    if (S.top == NULL)
    {
        return ERROR;
    }
    else
    {
        *e = S.top->data;
    }
    return OK;
}

//入栈
Status Push(LinkStack *S, SElemType e)
{
    LinkStackPtr s = (LinkStackPtr)malloc(sizeof(StackNode));
    s->data = e;
    s->next = S->top;
    S->top = s;
    S->cnt++;

    return OK;
}

//出栈
Status Pop(LinkStack *S, SElemType *e)
{
    if (StackEmpty(*S))
    {
        return ERROR;
    }
    LinkStackPtr p;
    *e = S->top->data;
    p = S->top;
    S->top = p->next;
    free(p);
    S->cnt--;

    return OK;
}

//遍历栈中所有元素
Status StackTraverse(LinkStack S)
{
    LinkStackPtr p;
    p = S.top;
    while (p)
    {
        visit(p->data);
        p = p->next;
    }

    printf("\n");

    return OK;
}